<template>
  <div class="page-container relative">
    <DynamicForm :config="tsConfig" :questions="tsQuestions" ref="tsForm"></DynamicForm>
    <DynamicTable :tables="tsTable" :config="tsTableConfig">
      <template #download="{ record }">
        <div class="actions">
          <span @click="preview(record)">预览</span>
          <span v-if="record.status === 2 && !record?.loading" @click="onDownload(record)">下载</span>
          <span v-if="record?.loading"><loading-outlined />下载中...</span>
          <span v-if="record.status === 4 && !record?.loading">下载</span>
        </div>
      </template>
    </DynamicTable>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, getCurrentInstance } from 'vue';
import { HOST } from '@/config';
import { useUserStoreWithOut } from '@/store/modules/user';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import HomeService from './index.service';
import { Api, fileTemplatePreview, fileTemplateDownload } from '@/config/api/fileTemplate';

const { proxy }: any = getCurrentInstance();
const tsConfig: any = {
  name: 'fileTable',
  labelCol: 6,
  wrapperCol: 18,
  grid: 8,
  style: 'table-form',
  cancelSave: true
};
const tsTableConfig: any = {
  name: 'fileTable',
  queryUrl: Api.fileTemplatePage,
  protType: 'post'
};
const tsQuestions: any = reactive(HomeService.getQuestions());
const tsTable: any = reactive(HomeService.getTables());
// 点击下载
const onDownload = (record) => {
  record.loading = true;
  const url = `${Api.fileTemplateDownload}/${record.currentVersionId}`;
  downloadFile(url, record);
};
// 预览
const preview = (record) => {
  const params = {
    id: record.currentVersionId,
    expires: 2,
    timeUnit: 'HOURS'
  };
  fileTemplatePreview(params).then((result) => {
    if (result && result.success) {
      window.open(result.data);
    }
  });
};
// 下列部分取消监听
// const subscribeSub = proxy.$NotificationPubSub
//   .getParams()
//   .pipe(filter((res) => res !== 0))
//   .subscribe((item: any) => {
//     if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '预览') {
//       const params = {
//         id: item.value.data.currentVersionId,
//         expires: 2,
//         timeUnit: 'HOURS'
//       };
//       fileTemplatePreview(params).then((result) => {
//         if (result && result.success) {
//           window.open(result.data);
//         }
//       });
//     } else if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '下载') {
//       const url = `${Api.fileTemplateDownload}/${item.value.data.currentVersionId}`;
//       // downloadFile(url);
//     }
//   });

const accessToken = useUserStoreWithOut().getToken;
const downloadFile = (url, record) => {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', `${HOST}${url}`, true);
  xhr.setRequestHeader('token', accessToken);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (this.status == 200) {
      const blob = new Blob([this.response], { type: 'contentType' });
      const contentDisposition = xhr.getResponseHeader('content-disposition');
      let filename = contentDisposition.substring(contentDisposition.indexOf('filename')).replace(/"/gi, '');
      filename = window.decodeURIComponent(filename.substring(filename.indexOf('=') + 1));
      const a = document.createElement('a');
      a.href = window.URL.createObjectURL(blob);
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(url);
      record.loading = false;
    }
  };
  xhr.onerror = function () {
    if (this.status !== 200) {
      record.loading = false;
    }
  };
  xhr.send();
};
// onBeforeUnmount(() => {
// subscribeSub && subscribeSub.unsubscribe();
// proxy.$NotificationPubSub.clearParams();
// });
</script>
<style lang="less" scoped>
.actions {
  display: flex;
  > span {
    margin-right: 10px;
    cursor: pointer;
    color: #005aea;
  }
}
</style>
